import React, { useState, useEffect } from 'react';
import * as echarts from 'echarts';

function MyGraph() {
  const [chart, setChart] = useState(null);
  const [nodes, setNodes] = useState([
    { id: '0', x: 100, y: 100 },
    { id: '1', x: 200, y: 200 },
    { id: '2', x: 300, y: 300 },
    { id: '3', x: 400, y: 400 },
    { id: '4', x: 500, y: 500 },
  ]);
  const [links, setLinks] = useState([
    { source: '0', target: '1' },
    { source: '1', target: '2' },
    { source: '2', target: '3' },
    { source: '3', target: '4' },
  ]);

  useEffect(() => {
    const chartInstance = echarts.init(document.getElementById('my-chart'));
    setChart(chartInstance);

    // 绘制图表，并手动指定节点位置
    chartInstance.setOption({
      series: [{
        type: 'graph',
        layout: 'none',
        data: nodes.map((node) => ({
          id: node.id,
          name: `Node ${node.id}`,
          x: node.x,
          y: node.y,
        })),
        links,
      }],
    });

    // 监听窗口变化事件，重新渲染图表
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      chartInstance.dispose();
    };
  }, []);

  function handleResize() {
    // 计算新的节点位置，并更新节点数据
    const newNodes = nodes.map((node) => {
      const oldX = node.x;
      const oldY = node.y;
      const newX = oldX / chart?.getWidth() * window.innerWidth;
      const newY = oldY / chart?.getHeight() * window.innerHeight;
      return {
        ...node,
        x: newX,
        y: newY,
      };
    });
    setNodes(newNodes);

    // 更新图表数据
    chart?.setOption({
      series: [{
        data: newNodes.map((node) => ({
          id: node.id,
          name: `Node ${node.id}`,
          x: node.x,
          y: node.y,
        })),
      }],
    });
  }

  return (
    <div id="my-chart" style={{ width: '100%', height: '500px' }}></div>
  );
}

export default MyGraph;
